'use strict';
layui.define(['jquery'], function(exports){
    let $ = layui.jquery;

    let obj = {
        content : null,
        nav : null,

        //初始化
        init: function(conf){
            this.content = conf.content;
            this.nav = conf.nav;

            //生成文章导航
            this.generate();


        },
        event: function(){
            //点击文章导航 添加激活class
            $(this.nav).find('p').on("click",function(){
                $(this).addClass("floatnav_a_cur").siblings().removeClass("floatnav_a_cur")
            });

            $(window).scroll(function() {
                $('.a-anchors').each(function (index, el) {
                    let aid = $(el).attr('href')
                        ,sh = $(window).scrollTop()
                        ,oP = $(aid);
                    if (oP.offset().top <= sh + oP.height()){
                        $(el).parent().addClass("floatnav_a_cur").siblings('p').removeClass('floatnav_a_cur');
                    }
                });
            });
        },
        //生成文章导航列表
        generate: function(){
            let that = this
                ,first = 'floatnav_a_cur';
            $(this.content).children().each(function(index, element) {
                let tagName=$(this).get(0).tagName;
                if(tagName.substr(0,1).toUpperCase() === "H"){

                    let contentH = that.getContent(this, that)
                        ,markid  = "mark-" + tagName + "-" + index.toString();
                    $(this).attr("id",markid);

                    let el = '';
                    switch (tagName) {
                        case 'H1':
                        case 'H2':
                        case 'H3':
                            el = '<p class="'+ first +'"><a class="a-anchors" href="#'+markid+'">'+contentH+'</a></p>';
                            break;
                        case 'H4':
                        case 'H5':
                        case 'H6':
                            el = '<p class="sec"><a class="sec a-anchors" href="#'+markid+'">'+contentH+'</a></p>';
                            break;
                    }
                    $(that.nav).append(el);
                    first = '';
                }
            });
            //生成结构以后 添加事件
            this.event();

        },
        getContent: function(el, obj){
            let text = '';

            $(el).contents().each(function (index, ele) {
                //如果是文本元素
                if (ele.nodeType === 3){
                    text = ele.nodeValue;

                }else{
                    text = obj.getContent(ele,obj);

                }
                return;
            });
            return text;
        }
    };


    //输出test接口
    exports('anchor', obj);
});